<!--
@fucntion: 关联
-->
<template>
  <div class="components-system-DepartmentFeeLtems">
    <el-row style="height:100%;">
      <el-col 
      style="height:100%;" :xs="24" :sm="24" :md="17" :lg="17">
        <table-panel :name="'类别'" 
        v-show="SwitchingPoint"
        :columns="DepartmentColumns" 
        :tableData="DepartmentData" 
        :canCreate="authorities.create" 
        :canDeleteAll="authorities.DeleteAll"
        :showRowNumber="true" 
        :canEdit="authorities.edit" 
        :canDelete="authorities.delete"
        :currentPage="DepartmentCurrentPage" 
        :totalNum="DepartmentTotalNum" 
        :canImport="authorities.Import"
        :action="actionUrl"
        :importFields="importField"
        @table-upload="onUpload"
        :canExport="authorities.export"
        :canDownTemplate="authorities.DownTemplate"
        @page-change="onPageChange('Department',$event)" 
        :pageSize="pageSize"
        @table-create="onCreate('Department',$event)" 
        @table-DeleteAll="onDeleteAll('Department',$event)" 
        @table-delete="onDelete('Department',$event)" 
        @table-export="onExport('Materials',$event)"
        @table-downTemplate="canDownTemplate('Materials',$event)"
        @table-edit="onEdit('Department', $event)"
        @table-searching="onSearching('Department',$event)"
        @current-change="onSelectionChange('Department',$event)">
        </table-panel>
        <el-col v-show="!SwitchingPoint">
          <el-card style="background-color: #DCDFE6;"> 
            <span v-if="(Ddata)" style="font-weight:bold;">类别信息添加</span>
            <span v-else style="font-weight:bold;">类别信息修改</span>
            <el-button type="warning" plain size="mini" style="float:right" 
              @click="onConfirm('Department')">
              <span v-if="(Ddata)" style="font-weight:bold;">确认添加</span>
              <span v-else style="font-weight:bold;">确认修改</span>
            </el-button> 
            <el-button v-if="(Ddata)" type="danger"  plain size="mini" style="float:right" 
              @click="DetailedData = {};">重置</el-button>
            <el-button plain size="mini" style="float:right" 
              @click="SwitchingPoint = !(SwitchingPoint);">返回
            </el-button> 
          </el-card>
          <el-form ref="DetailedData" 
          :model="DetailedData" 
          :rules="rules" 
          label-position="right" 
          label-width="105px" 
          size="mini" 
          status-icon>
          <el-card style="width: 100%;height:600px;">
            <el-card>
              <el-form-item label="自定义编号" prop="categoryDefinedId">
                <el-input  v-model="DetailedData.categoryDefinedId"></el-input>
              </el-form-item>
              <el-form-item label="类别名称" prop="categoryName">
                <el-input  v-model="DetailedData.categoryName"></el-input>
              </el-form-item>
              <el-form-item label="备注" prop="notes">
                <el-input
                      type="textarea"
                      :autosize="{ minRows:2 , maxRows: 5}"
                      placeholder="请输入内容"
                      maxlength="50"
                      show-word-limit
                      v-model="DetailedData.notes">
                </el-input>
              </el-form-item>
            </el-card>    
          </el-card>
          </el-form>
        </el-col>
      </el-col>
      <el-col style="height:100%;" :xs="24" :sm="24" :md="7" :lg="7">
        <simple-panel 
        v-show="SwitchingPoint2"
        :panelTitle="'耗材信息'" 
        :hasToolbar="true">
          <template slot="toolbar">
            <grid-search 
            :tableColumns="FeeLtemsColumns" 
            @searching="onSearching2('FeeLtems',$event)"></grid-search>
            <el-button v-show="authorities.save" style="margin:7px 15px;" size="mini" @click="onSave" type="warning">关联</el-button>
          </template>
          <template slot="main">
            <el-table ref="FeeLtemsTable" :data="FeeLtemsData" :height="665" style="width: 100%" size="medium"
            order stripe border
            @selection-change="onSelectionChange('FeeLtems',$event)">
              <el-table-column type="selection" width="50" fixed="left"></el-table-column>
              <!-- <el-table-column label="" type="index" width="50" fixed="left"></el-table-column> -->
              <template v-for="(col, index) in FeeLtemsColumns">
                <el-table-column v-if="!col.hidden" :key="index" :prop="col.prop" :label="col.label" :width="col.width"
                :align="col.align?col.align:'left'" :header-align="col.headerAlign?col.headerAlign:'left'">
                  <template slot-scope="scope">
                    <span v-if="col.renderer" v-html="col.renderer(scope,col.prop)">
                    </span>
                    <span v-else v-text="scope.row[col.prop]">
                    </span>
                  </template>
                </el-table-column>
              </template>
              <el-table-column label="操作" width="60" fixed="right">
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="onEditRange(scope.row)">详情</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </simple-panel>
        <el-col v-show="!SwitchingPoint2">
          <el-card style="background-color: #DCDFE6;"> 
            <span style="font-weight:bold;">耗材信息详情</span>
            <el-button plain size="mini" style="float:right" 
              @click="SwitchingPoint2 = !(SwitchingPoint2);">返回
            </el-button> 
          </el-card>
          <el-form ref="DetailedData2" 
          :model="DetailedData2"  
          label-position="right" 
          label-width="105px" 
          size="mini" 
          status-icon>
          <el-card style="width: 100%;height:100%;">
            <el-card>
              <el-form-item label="自定义编号">
                <el-input  v-model="DetailedData2.medicalConsumableDefinedId" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="耗材名称">
                <el-input  v-model="DetailedData2.medicalConsumableName" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="规格型号">
                <el-input  v-model="DetailedData2.specifications" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="生产厂家">
                <el-input  v-model="DetailedData2.productionPlace" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="单价">
                <el-input  v-model="DetailedData2.price" :readonly="true"><template slot="append">{{DetailedData2.unit}}</template></el-input>
              </el-form-item>
              <el-form-item label="单位">
                <el-input  v-model="DetailedData2.unit" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="收入项目">
                <el-input  v-model="DetailedData2.entitlementSpending" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="供应商编码">
                <el-input  v-model="DetailedData2.providerId" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="供应商名称">
                <el-input  v-model="DetailedData2.providerName" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="物资类别">
                <el-input  v-model="DetailedData2.suppliesCategory" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="会计科目">
                <el-input  v-model="DetailedData2.accountTitle" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="国产进口">
                <el-input  v-model="DetailedData2.domesticImports" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="合同号">
                <el-input  v-model="DetailedData2.contractNo" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="耗材使用">
                <el-input  v-model="DetailedData2.medicalConsumableUsing" :readonly="true"><template slot="append">%</template></el-input>
              </el-form-item>
              <el-form-item label="是否高值">
                <el-switch
                  v-model="DetailedData2.highValueConsumables"
                  disabled
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
              <el-form-item label="是否收费">
                <el-switch
                  v-model="DetailedData2.charge"
                  disabled
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
              <el-form-item label="是否代销">
                <el-switch
                  v-model="DetailedData2.sale"
                  disabled
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
              <el-form-item label="备注" :readonly="true">
                <el-input
                      type="textarea"
                      :autosize="{ minRows:3 , maxRows: 5}"
                      placeholder="请输入内容"
                      maxlength="50"
                      show-word-limit
                      v-model="DetailedData2.notes">
                </el-input>
              </el-form-item>
            </el-card>    
          </el-card>
          </el-form>
        </el-col>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import TablePanel from "@/components/basic/TablePanel";
import SimplePanel from "@/components/basic/SimplePanel";
import GridSearch from "@/components/basic/GridSearch";
import {
  formModelInitFromTable,
  formRulesInitFromTable
} from "@/utils/formutils.js";
import {
  trueFalseRenderer,
  findRowsByKeys
} from "@/utils/tableutils.js";

//meta info
var Department = "Department";// 表格名称
var FeeLtems = "FeeLtems";
var columnsAttr = "Columns";// 列
var dataAttr = "Data";// 数据
var selectionAttr = "Selection";// 选中
var dlgVisibleAttr = "DlgVisible";// 对话框
var formAttr = "Form";
var recordAttr = "Record";// 表单模型
var rulesAttr = "Rules";// 表单验证
var curPageAttr = "CurrentPage";// 分页-当前页
var totalNumAttr = "TotalNum";// 分页-总数
var qParamAttr = "QueryParams";// 查询参数

// -列
var DepartmentColumns = [
  {
  prop: "categoryId",
  label: "编号",
  outOfSearch:true,
  hidden: true,
  }, 
  {
    prop: "categoryDefinedId",
    label: "自定义编号",
  },
  {
    prop: "categoryName",
    label: "类别名称",
  },
  {
    prop: "notes",
    label: "备注",
    hidden: true,
  },
];

// -列
var FeeLtemsColumns = [
  {
  prop: "medicalConsumableId                       ",
  label: "编号",
  outOfSearch:true,
  hidden: true,
  }, 
  {
    prop: "medicalConsumableDefinedId",
    label: "编号",
    width:55,
  },
  {
    prop: "medicalConsumableName",
    label: "耗材名称",
  }
  , 
  {
    prop: "specifications",
    label: "规格型号",
    hidden: true,
  },
  {
    prop: "productionPlace",
    label: "生产厂家",
    hidden: true,
  }
  , 
  {
    prop: "price",
    label: "单价",
    outOfSearch:true,
    hidden: true,
  },
  {
    prop: "unit",
    label: "单位",
    outOfSearch:true,
    hidden: true,
  }
  , 
  {
    prop: "entitlementSpending",
    label: "收入项目",
    hidden: true,
  },
  {
    prop: "providerId",
    label: "供应商编码",
    outOfSearch:true,
    hidden: true,
  }
  , 
  {
    prop: "providerName",
    label: "供应商",//名称
    hidden: true,
  },
  {
    prop: "suppliesCategory",
    label: "物资类别",
    hidden: true,
  }
  , 
  {
    prop: "accountTitle",
    label: "会计科目",
    outOfSearch:true,
    hidden: true,
  },
  {
    prop: "domesticImports",
    label: "国产进口",
    hidden: true,
  }
  , 
  {
    prop: "contractNo",
    label: "合同号",
    outOfSearch:true,
    hidden: true,
  },
  {
    prop: "highValueConsumables",
    label: "是否高值",
    hidden: true,
  }
  , 
  {
    prop: "charge",
    label: "是否收费",
    hidden: true,
  },
  {
    prop: "sale",
    label: "是否代销",
    hidden: true,
  },
  {
    prop: "notes",
    label: "备注",
    outOfSearch:true,
    hidden: true,
  },
  {
    prop: "medicalConsumableUsing",
    label: "耗材使用",
    outOfSearch:true,
    hidden: true,
  }
];

//导入
var importField = [
 "编号",
 "自定义编号",
 "类别名称",
 "备注",
];
//导出
var exportField = [
 "编号",
 "自定义编号",
 "类别名称",
 "备注",
];

export default {
  // 使用其他子组件
  components: {
    "table-panel": TablePanel,
    "simple-panel":SimplePanel,
    "grid-search": GridSearch
  },
  methods:{
    onSearching: function(tname, params) {// 查询
      var me = this;
      let url = "/static/data/TypeOfConsumables.json";// /static/data/TypeOfConsumables.json      jcJsxxb

      if(url !== "") {
        me[tname+qParamAttr] = {};
        me[tname+qParamAttr] = params;
        if (params.isAccurate) {
          me[tname+qParamAttr] = params.paramPairs;
        } else {
          me[tname+qParamAttr].keywords = params.query;
        }
        me.getRequest(url, me[tname+qParamAttr]).then(resp => {
            if(resp.status == 200) {
              me[tname+dataAttr] = resp.data.results;
              me[tname+totalNumAttr] = resp.data.total;// 分页-总数
              this.pageSize = resp.data.limit;//每页数量
              me[tname+curPageAttr] = resp.data.offset;//起始页    results
            }
        });
      }

    },
    onSearching2: function(tname, params) {// 查询-右部分
      var me = this;
      let url = "/static/data/TypeOfConsumables2.json";// /static/data/DepartmentFeeItems.json      jcJsxxb

      if(url !== "") {
        me[tname+qParamAttr] = {};
        me[tname+qParamAttr] = params;
        if (params.isAccurate) {
          me[tname+qParamAttr] = params.paramPairs;
        } else {
          me[tname+qParamAttr].keywords = params.query;
        }
        me.getRequest(url, me[tname+qParamAttr]).then(resp => {
            if(resp.status == 200) {
              me[tname+dataAttr] = resp.data.results;
              // // me[tname+totalNumAttr] = resp.data.total;// 分页-总数

              // me[tname+totalNumAttr] = resp.data.total;// 分页-总数
              // this.pageSize = resp.data.limit;//每页数量
              // me[tname+curPageAttr] = resp.data.offset;//起始页    results
            }
        });
      }

    },
    onCreate: function(tname) {// 新增
      var me = this;
      me[tname + dlgVisibleAttr] = true;
      me[tname + recordAttr] = formModelInitFromTable(me[tname + columnsAttr]);
      this.DetailedData = {};
      this.Ddata = true;
      this.SwitchingPoint = !(this.SwitchingPoint);
    },
    onEdit: function(tname, row) {// 编辑
      var me = this;
      me[tname + dlgVisibleAttr] = true;
      me[tname + recordAttr] = row;
      this.Ddata = false;
      this.SwitchingPoint = !(this.SwitchingPoint);
      this.DetailedData = row
    },
    onEditRange: function(row) {// 详情-右部分
      this.SwitchingPoint2 = !(this.SwitchingPoint2);
      this.DetailedData2 = row
    },
    onDelete: function(tname, row) {// 删除
      var me = this;
      me.$confirm("确定删除这条记录吗?", "提示", {
          type: "warning"
      }).then(() => {
          me.deleteRequest(`/api/${row.categoryId}`).then((resp)=>{
            if(resp.status == 200) {
              me.$message.success("删除成功!");
              me.onSearching(Department,{});// 重新加载表格数据
            }else{
              me.$message.error('删除失败！');
            }
          });
      }).catch(() => {});
    },
    onDeleteAll:function(tname, row){//全部删除
      var me = this;
      me.$confirm("确定删除全部记录吗?", "提示", {
          type: "warning"
      }).then(() => {
          me.deleteRequest(`/api`).then((resp)=>{
            if(resp.status == 200) {
              me.$message.success("删除成功!");
              me.onSearching(Department,{});// 重新加载表格数据
            }else{
              me.$message.error('删除失败！');
            }
          });
      }).catch(() => {});
    },
    onConfirm: function(tname) {// 对话框-确认
      let me = this;
      // 发送请求 /jcJsxxb

      if(me[Department + recordAttr].categoryId == ""){

        me.$confirm("确定新增记录吗?", "提示", {
          type: "warning"
        }).then(() => {
          me.postRequest("/jXxxb",me[Department + recordAttr]).then(resp => {
            if (resp.status == 200) {
              me.$message.success("提交成功！");

              //最后，隐藏对话框
              me[tname + dlgVisibleAttr] = false;
              this.SwitchingPoint = !(this.SwitchingPoint);
              me.onSearching(Department, {});// 重新查一遍
            } else {
              me.$message.error("服务器发生错误，代码：" + resp.status);
            }
          });
        }).catch(() => {});
      }else{

        me.$confirm("确定修改记录吗?", "提示", {
          type: "warning"
        }).then(() => {
          me.postRequest("/jXxxb",me[Department + recordAttr]).then(resp => {
            if (resp.status == 200) {
              me.$message.success("提交成功！");

              //最后，隐藏对话框
              me[tname + dlgVisibleAttr] = false;
              this.SwitchingPoint = !(this.SwitchingPoint);
              me.onSearching(Department, {});// 重新查一遍
            } else {
              me.$message.error("服务器发生错误，代码：" + resp.status);
            }
          });
        }).catch(() => {});
      }
    },
    onExport: function(tableName, params) {// 导出
      var me = this;
      const h = me.$createElement;
      me.$notify.info({
        title: "提示",
        message: h("i", { style: "color: teal" }, "正在导出数据，请稍等……")
      });
      me.exportRequest("/sbxxgl/export", {
        fields: JSON.stringify(exportField),//exportField
        sfbf: false
      }).then(resp => {
        if (resp.status === 200) {
          me.$notify.success({
            title: "提示",
            message: h("i", { style: "color: #67C23A" }, "数据导出成功")
          });
          downExcel(resp);
        } else {
          me.$notify.success({
            title: "提示",
            message: h("i", { style: "color: #F56C6C" }, "数据导出失败")
          });
        }
      });
    },
    onUpload:function(msg,flag){//导入
      var me = this;
      if(flag){
        me.currentPage = 1;
        me.onSearching('sbxxgl',{page:me.currentPage,size:me.pageSize});
      }
    },
    onDownTemplate:function(tableName, params){//模板下载
      var me = this;
      const h = me.$createElement;
      me.$notify.info({
        title: '提示',
        message: h('i', { style: 'color: teal'}, '正在下载模板，请稍等……')
      });
      me.downFileRequest('/excelTemplate/类别信息.xlsx').then(resp=>{
        me.$notify.success({
          title: '提示',
          message: h('i', { style: 'color: #67C23A'}, '模板下载成功')
        });
          fileDownload(resp.data,"类别信息.xlsx");
      });
    },
    onSelectionChange: function(tname, data) {// 选中改变
      var me = this;
      if(tname === Department){
        // 缓存记录，按照类别编号，查询对应的选中权限节点数组
        me[tname+selectionAttr] = data;
        // 先清空上一次选中的
        me.$refs.FeeLtemsTable.clearSelection();
        // 然后加载新的关联并显示 /static/data/system/DepartmentFeeLtemsSelected.json
        me.getRequest("/sysJsxxb/categoryIds",{
          categoryId:data.categoryId
        }).then((resp)=>{
          if(resp.status == 200){
            // 按照categoryId-类别编号-选中对应记录 resp.data.data
            let keys = me.arrUtil.transObjArrToSimpleArr(resp.data,"categoryId");
            let rows = findRowsByKeys(me[FeeLtems+dataAttr],"categoryId", keys);
            rows.forEach(row => {
              me.$refs.FeeLtemsTable.toggleRowSelection(row, true);
            });

          }else {
            me.$message.error("服务器读取错误，没有找到该类别所关联的耗材信息！");
          }
        });
      }else if(tname === FeeLtems){
        me[tname+selectionAttr] = data;
      }

    },
    onSave:function() {// 保存关联
      var me = this;
      var FeeLtemssSelected = me[FeeLtems+selectionAttr];// 选中的耗材信息
      var DepartmentSelected = me[Department+selectionAttr];// 选中的类别
      // 验证
      if(FeeLtemssSelected.length < 1){
        me.$message.warning("请至少选择一条耗材信息！");
        return;
      }
      console.log("DepartmentSelected=",DepartmentSelected);
      if(!DepartmentSelected.categoryId || DepartmentSelected.categoryId == ""){
        me.$message.warning("请选择一个类别！");
        return;
      }
      console.log("FeeLtemssSelected=",FeeLtemssSelected);
      let categoryIdArr = [];
      for (let i = 0; i < FeeLtemssSelected.length; i++) {
        const FeeLtems = FeeLtemssSelected[i];
        categoryIdArr.push(FeeLtems.categoryId);
      }

      // 发送数据 /static/data/testSuc.json
      me.postRequest("/jcYhxxb/sysYhjsglxxb",{
        categoryId:DepartmentSelected.categoryId,
        categoryIds:categoryIdArr.toString()
      }).then((resp)=>{
        if (resp.status == 200) {
          me.$message.success(resp.data.msg);
        } else{
          me.$message.error("服务器发生错误，代码：" + resp.status);
        }
      });
    }
  },
  data(){
    return {
      authorities:{
        create:true,
        DeleteAll:true,
        edit:true,
        delete:true,
        save:true,
        Import:true,
        DownTemplate:true,
        export:true,
      },// 权限控制
      [Department+columnsAttr]: DepartmentColumns,// 角色表格-列
      [Department+dataAttr]: [],// 角色表格的数据
      [Department+selectionAttr]:{},// 当前选中的角色
      [FeeLtems+columnsAttr]: FeeLtemsColumns,// 角色表格-列
      [FeeLtems+dataAttr]: [],// 角色表格的数据
      [FeeLtems+selectionAttr]:[],// 当前选中的角色
      [Department+curPageAttr]:1,
      [Department+totalNumAttr]:0,
      [Department+qParamAttr]:{},
      pageSize:20,// 每页数量

      importField:importField.join(","),//导入的字段

      SwitchingPoint:true,//表单列表之间-切换控制
      DetailedData:{},//存储表单中的数据

      SwitchingPoint2:true,//表单列表之间-切换控制-右边部分
      DetailedData2:{},//存储表单中的数据-右边部分

      Ddata:true,//控制表单头标题的显示内容

      actionUrl:"/sbxxgl/import",//导入的路径

      rules: {
          categoryDefinedId: [
            { required: true, message: '请输入自定义编号', trigger: 'blur' },
            ],
          categoryName: [
            { required: true, message: '请输入类别名称', trigger: 'blur' },
            { min: 1, max: 50, message: '长度最大为50个字符', trigger: 'blur' }
           ],
          notes: [
            { required: true, message: '请填写备注', trigger: 'blur' },
          ]
        }
    };
  },
  created: function() {
    var me = this;
    // 添加权限控制
    // me.authorities = me.$route.meta.authorities;

    // 一开始就加载角色列表
    me.onSearching2(FeeLtems,{});

    me.onSearching(Department,{});
  }
}
</script>
<style lang="scss">

.components-system-DepartmentFeeLtems{
  height:100%;
}

</style>
